package com.example.sso.server.controller;

import com.example.sso.server.entity.ClientApp;
import com.example.sso.server.entity.User;
import com.example.sso.server.repository.ClientAppRepository;
import com.example.sso.server.repository.TokenRepository;
import com.example.sso.server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class LoginController {

    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ClientAppRepository clientAppRepository;
    
    @Autowired
    private TokenRepository tokenRepository;

    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpSession session,
            Model model) {
        
        // 验证用户
        if (!userRepository.validateUser(username, password)) {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
        
        // 验证通过，将用户信息存入session
        session.setAttribute("username", username);
        
        // 检查是否有授权请求
        String clientId = (String) session.getAttribute("clientId");
        String redirectUri = (String) session.getAttribute("redirectUri");
        String state = (String) session.getAttribute("state");
        String referer = (String) session.getAttribute("referer");
        
        if (clientId != null && redirectUri != null) {
            // 清除session中的授权请求信息
            session.removeAttribute("clientId");
            session.removeAttribute("redirectUri");
            session.removeAttribute("state");
            session.removeAttribute("referer");
            
            // 生成授权码
            String code = tokenRepository.generateCode();
            
            // 构建重定向URL
            StringBuilder redirectUrl = new StringBuilder(redirectUri);
            if (redirectUri.contains("?")) {
                redirectUrl.append("&");
            } else {
                redirectUrl.append("?");
            }
            redirectUrl.append("code=").append(code);
            
            if (state != null) {
                redirectUrl.append("&state=").append(state);
            }
            
            if (referer != null) {
                redirectUrl.append("&Referer=").append(URLEncoder.encode(referer, StandardCharsets.UTF_8));
            }
            
            return "redirect:" + redirectUrl.toString();
        }
        
        // 没有授权请求，直接跳转到用户信息页面
        return "redirect:/userinfo";
    }
    
    @GetMapping("/userinfo")
    public String userInfo(HttpSession session, Model model) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return "redirect:/login";
        }
        
        User user = userRepository.findByUsername(username);
        model.addAttribute("user", user);
        return "userinfo";
    }
    
    @GetMapping("/ssologout")
    public String logout(
            @RequestParam("Referer") String referer,
            HttpSession session) {
        
        // 清除session
        session.invalidate();
        
        // 重定向到客户端
        return "redirect:" + referer;
    }
}
    